import { defineStore } from 'pinia'
import * as api from '@/api/user'

export const userStore = defineStore('userStore', {
  state: () => ({
    // 用户信息
    user: {},
    token: localStorage.getItem('token') || '',
    refreshToken: localStorage.getItem('refresh_token') || '',
    
    //用户列表
    userList: [],
    // 分页参数 order、asc
    // order=&asc=false&page=1&limit=10&username=&mobile=&gender=
    pagination: {
      page: 1,
      limit: 7,
      total: 0,
    },
  }),
  getters: {
    hasUser() {
      return JSON.stringify(this.user) !== '{}'
    }
  }, 
  actions: {
    setToken(token) {
        this.token = token
        localStorage.setItem('token', token)
    },

    setRefreshToken(refreshToken) {
        this.refreshToken = refreshToken
        localStorage.setItem('refresh_token', refreshToken)
    },

    async getLogin(loginForm) {
      try {
          const res = await api.login(loginForm)
          this.setToken(res.access_token)
          this.setRefreshToken(res.refresh_token)
          // return res
      } catch (error) {
          throw new Error(error.message || '登录请求失败')
      }
    },

    async getUserInfo() {
      try {
        const res = await api.getUserInfo()
        this.user = res
        return res
      } catch(error) {
        if (error.code === 401) {
          this.setToken(null)  // 清除token
          this.setRefreshToken(null)
          localStorage.clear()
          throw new Error('Unauthorized') // 抛出错误
        } else {
          throw error
        }
      }
    },

    async logout() {
      try {
        await api.logout()
        this.setToken(null)
        this.setRefreshToken(null)
        window.localStorage.clear()
        // TODO 清理缓存及相关权限
      } catch(error) {
        throw error
      }
    },

    async getUserList(param) {
      try {
        const params = {
            ...param,
            page: this.pagination.page,
            limit: this.pagination.limit
        }
        const res = await api.getUserList(params)
        // console.log(res)
        this.userList = res.list
        this.pagination.total = res.total
        // return res
      } catch(error) {
        throw error
      }
    },

    async addUser(userForm) {
      try {
        const res = await api.addUser(userForm)
        return res
      } catch(error) {
        throw error
      }
    },

    async updateUser(userForm) {
      try {
        const res = await api.updateUser(userForm)
        return res
      } catch(error) {
        throw error
      }
    },

    async deleteUser(ids) {
      try {
        const res = await api.deleteUser(ids)
        return res
      } catch(error) {
        throw error
      }
    },

    async getUserOne(id) {
      try {
        const res = await api.getUser(id)
        return res
      } catch(error) {
        throw error
      }
    },

    async updateUserInfo(formData) {
      try {
        const res = await api.updateUserInfo(formData)
        return res
      } catch(error) {
        throw error
      }
    }
  }

})
